package org.msfj.authority.client.interceptor;

import cn.hutool.core.util.StrUtil;
import org.msfj.authority.client.config.ClientAuthConfig;
import org.msfj.authority.client.util.ClientSecureUtil;
import org.msfj.common.annotation.Constants;
import org.msfj.common.context.MemberContextHandler;
import org.msfj.common.context.UserContextHandler;
import org.msfj.common.exception.ClientForbiddenException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by ace on 2017/9/10.
 */
public class ClientAuthRestInterceptor extends HandlerInterceptorAdapter {
    private Logger logger = LoggerFactory.getLogger(ClientAuthRestInterceptor.class);

    @Autowired
    private ClientAuthConfig clientAuthConfig;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userId = request.getHeader(Constants.CONTEXT_KEY_USER_ID);
        if (StrUtil.isNotBlank(userId)) {
            UserContextHandler.setUserID(userId);
        }
        //解决前台向数据库新增修改数据时createBy和updateBy没有值的问题
        if (StrUtil.isBlank(UserContextHandler.getUserID())) {
            UserContextHandler.setUserID("0");
        }
        String memberId = request.getHeader(Constants.CONTEXT_KEY_MEMBER_ID);
        if (StrUtil.isNotBlank(memberId)) {
            MemberContextHandler.setMemberID(memberId);
        }

        String token = request.getHeader(clientAuthConfig.getTokenHeader());
        logger.trace("请求 " + request.getRequestURI() + " 携带的["+clientAuthConfig.getTokenHeader()+"] 为：" + token);
        if (StrUtil.isNotBlank(token)) {
            if (ClientSecureUtil.isValidate(token)) {
                return super.preHandle(request, response, handler);
            } else {
                logger.error("请求 " + request.getRequestURI() + " token 错误");
                throw new ClientForbiddenException("请求 " + request.getRequestURI() + " token 错误");
            }
        } else {
            logger.error("请求 " + request.getRequestURI() + " token 为空");
            throw new ClientForbiddenException("请求 " + request.getRequestURI() + " token 为空");
        }
    }
}
